import 'dart:async';

import 'package:catsao/mock/video.dart';
import 'package:catsao/pages/userDetailPage.dart';
import 'package:catsao/style/style.dart';
import 'package:catsao/style/theme.dart';
import 'package:catsao/views/VideoThumbnail.dart';
import 'package:catsao/views/topToolRow.dart';
import 'package:flutter/material.dart';
import 'package:tapped/tapped.dart';
import 'package:http/http.dart' as http;
import 'package:fluwx/fluwx.dart' as fluwx;
import 'dart:typed_data';
import 'TictokhomePage.dart';
import 'followPage.dart';

class UserPage extends StatefulWidget {
  final bool canPop;
  final bool isSelfPage;
  final Function onPop;
  final Function onSwitch;

  const UserPage({
    Key key,
    this.canPop: false,
    this.onPop,
    @required this.isSelfPage,
    this.onSwitch,
  }) : super(key: key);

  @override
  _UserPageState createState() => _UserPageState();
}

class _UserPageState extends State<UserPage> {
  String _result = "无";
  List<UserVideo> videoDataList = [];

  @override
  void initState() {
    videoDataList = UserVideo.fetchVideo();
    super.initState();
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        setState(() {
          _result = res.code;
        });
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    Widget likeButton = Container(
      color: ColorPlate.back1,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        mainAxisAlignment: MainAxisAlignment.end,
        children: <Widget>[
          Tapped(
            child: _UserRightButton(
              title: widget.isSelfPage ? '钱包' : '关注',
            ),
          ),
          OutlineButton(
            onPressed: () async {
              var result = await fluwx.isWeChatInstalled;
              if (result) {
                // fluwx
                //     .sendWeChatAuth(
                //         scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
                //     .then((data) {
                //   Timer(const Duration(seconds: 1), () {
                //     httpgettoken(_result);
                //   });
                // });
                httpgettoken();
              } else {
                showDialog<Null>(
                    context: context,
                    builder: (BuildContext context) {
                      return new AlertDialog(
                        title: new Text("提示"),
                        content: new SingleChildScrollView(
                          child: new ListBody(
                            children: <Widget>[new Text("该手机还没有安装微信")],
                          ),
                        ),
                        actions: <Widget>[
                          new FlatButton(
                            child: new Text("确定"),
                            onPressed: () {
                              Navigator.of(context).pop();
                            },
                          )
                        ],
                      );
                    });
              }
            },
            child: const Text("send auth"),
          ),
          const Text("响应结果;"),
          Text("$_result"),
        ],
      ),
    );
    Widget avatar = Container(
      height: 120 + MediaQuery.of(context).padding.top,
      padding: EdgeInsets.only(left: 18),
      alignment: Alignment.bottomLeft,
      child: OverflowBox(
        alignment: Alignment.bottomLeft,
        minHeight: 20,
        maxHeight: 300,
        child: Container(
          height: 74,
          width: 74,
          margin: EdgeInsets.only(bottom: 12),
          decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(44),
            color: Colors.orange,
            border: Border.all(
              color: Colors.white,
              width: 1,
            ),
          ),
          child: ClipOval(
            child: Image.network(
              "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif",
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
    );
    Widget body = ListView(
      physics: BouncingScrollPhysics(
        parent: AlwaysScrollableScrollPhysics(),
      ),
      children: <Widget>[
        Container(height: 20),
        // 头像与关注
        Stack(
          alignment: Alignment.bottomLeft,
          children: <Widget>[likeButton, avatar],
        ),
        Container(
          color: ColorPlate.back1,
          child: Column(
            children: <Widget>[
              Container(
                padding: EdgeInsets.only(left: 18),
                color: ColorPlate.back1,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    Text(
                      '@用户名',
                      style: StandardTextStyle.big.apply(
                        color: Colors.white,
                      ),
                    ),
                    Container(height: 8),
                    Text(
                      '朴实无华，且枯燥',
                      style: StandardTextStyle.smallWithOpacity.apply(
                        color: Colors.white,
                      ),
                    ),
                    Container(height: 10),
                    Row(
                      children: <Widget>[
                        _UserTag(tag: '幽默'),
                        _UserTag(tag: '机智'),
                        _UserTag(tag: '枯燥'),
                        _UserTag(tag: '狮子座'),
                      ],
                    ),
                    Container(height: 10),
                  ],
                ),
              ),
              Container(
                color: ColorPlate.back1,
                padding: EdgeInsets.symmetric(
                  horizontal: 8,
                  vertical: 2,
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    TextGroup(
                      '356',
                      '关注',
                      color: Colors.white,
                    ),
                    TextGroup(
                      '145万',
                      '粉丝',
                      color: Colors.white,
                    ),
                    TextGroup(
                      '1423万',
                      '获赞',
                      color: Colors.white,
                    ),
                  ],
                ),
              ),
              Container(
                height: 10,
                margin: EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                  border: Border(
                    bottom: BorderSide(
                      color: Colors.white.withOpacity(0.1),
                    ),
                  ),
                ),
              ),
              _UserVideoTable(
                uservideolist: videoDataList,
              ),
            ],
          ),
        ),
      ],
    );
    return Container(
      decoration: BoxDecoration(
        gradient: LinearGradient(
          begin: Alignment.topCenter,
          colors: <Color>[
            Colors.orange,
            Colors.red,
          ],
        ),
      ),
      child: Stack(
        alignment: Alignment.topCenter,
        children: <Widget>[
          Container(
            margin: EdgeInsets.only(top: 400),
            height: double.infinity,
            width: double.infinity,
            color: ColorPlate.back1,
          ),
          body,
          Container(
            margin: EdgeInsets.only(top: 20),
            height: 62,
            child: TopToolRow(
              canPop: widget.canPop,
              onPop: widget.onPop,
              right: Tapped(
                child: Container(
                  width: 30,
                  height: 30,
                  margin: EdgeInsets.all(16),
                  decoration: BoxDecoration(
                    color: Colors.black.withOpacity(0.36),
                    borderRadius: BorderRadius.circular(15),
                  ),
                  alignment: Alignment.center,
                  child: Icon(
                    Icons.more_horiz,
                    size: 24,
                    color: Colors.white,
                  ),
                ),
                onTap: () {
                  Navigator.of(context).push(MaterialPageRoute(builder: (ctx) {
                    return Theme(
                      data: ThemeColor.themecolor,
                      child: UserDetailPage(),
                    );
                  }));
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _UserRightButton extends StatelessWidget {
  const _UserRightButton({
    Key key,
    @required this.title,
  }) : super(key: key);

  final String title;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(
        vertical: 6,
        horizontal: 20,
      ),
      margin: EdgeInsets.all(8),
      alignment: Alignment.center,
      child: Text(
        title ?? '',
        style: TextStyle(color: ColorPlate.orange),
      ),
      decoration: BoxDecoration(
        border: Border.all(color: ColorPlate.orange),
        borderRadius: BorderRadius.circular(4),
      ),
    );
  }
}

class _UserTag extends StatelessWidget {
  final String tag;

  const _UserTag({
    Key key,
    this.tag,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 4),
      padding: EdgeInsets.symmetric(
        vertical: 2,
        horizontal: 4,
      ),
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.white.withOpacity(0.3),
        ),
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        tag ?? '标签',
        style: StandardTextStyle.smallWithOpacity,
      ),
    );
  }
}

class _UserVideoTable extends StatelessWidget {
  const _UserVideoTable({Key key, this.uservideolist}) : super(key: key);

  final List<UserVideo> uservideolist;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Container(
          color: ColorPlate.back1,
          padding: EdgeInsets.symmetric(
            vertical: 12,
          ),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              _PointSelectTextButton(
                true,
                '作品',
              ),
              _PointSelectTextButton(false, '关注'),
              _PointSelectTextButton(false, '喜欢'),
            ],
          ),
        ),
        GridView.builder(
          shrinkWrap: true,
          physics: new NeverScrollableScrollPhysics(),
          //禁用滑动事件
          scrollDirection: Axis.vertical,
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3, //每行三列
            mainAxisSpacing: 3,
            crossAxisSpacing: 2,

            childAspectRatio: 3.55 / 5,
          ),
          itemCount: uservideolist.length,
          itemBuilder: (context, index) {
            return SizedBox(
              width: double.infinity,
              height: 10,
              child: _SmallVideo(
                uservideo: uservideolist[index],
                index: index,
              ),
            );
          },
        ),
        Container(
          child: SizedBox(
            width: double.infinity,
            height: 10,
            child: Text(""),
          ),
        )
      ],
    );
  }
}

class _SmallVideo extends StatelessWidget {
  const _SmallVideo({Key key, this.uservideo, this.index}) : super(key: key);

  final UserVideo uservideo;
  final int index;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        Expanded(
            child: GestureDetector(
          child: Container(
              // decoration: BoxDecoration(
              //   border: Border.all(color: Colors.black12),
              // ),
              alignment: Alignment.center,
              child: VideoThumbnail(
                videourl: uservideo.url,
                aspectRatiowidth: 1,
                aspectRatioheight: 1,
              )),
          onTap: () {
            Navigator.push(context, MaterialPageRoute(builder: (context) {
              return new TictokHomePage(
                currentvideoid: index,
                showheader: false,
              );
            }));
          },
        ))
      ],
    );
  }
}

class _PointSelectTextButton extends StatelessWidget {
  final bool isSelect;
  final String title;
  final Function onTap;

  const _PointSelectTextButton(
    this.isSelect,
    this.title, {
    Key key,
    this.onTap,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Expanded(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          isSelect
              ? Container(
                  width: 6,
                  height: 6,
                  decoration: BoxDecoration(
                    color: ColorPlate.orange,
                    borderRadius: BorderRadius.circular(3),
                  ),
                )
              : Container(),
          Container(
            padding: EdgeInsets.only(left: 2),
            child: Text(
              title,
              style: isSelect
                  ? StandardTextStyle.small.apply(
                      color: Colors.white,
                    )
                  : StandardTextStyle.smallWithOpacity,
            ),
          )
        ],
      ),
    );
  }
}

// class _IconTextButton extends StatelessWidget {
//   final IconData icon;
//   final String title;
//   final Function onTap;
//   const _IconTextButton(
//     this.icon,
//     this.title, {
//     Key key,
//     this.onTap,
//   }) : super(key: key);

//   @override
//   Widget build(BuildContext context) {
//     return Container(
//       padding: EdgeInsets.symmetric(vertical: 12),
//       child: Row(
//         mainAxisAlignment: MainAxisAlignment.center,
//         children: <Widget>[
//           Icon(icon, color: ColorPlate.yellow),
//           Container(
//             padding: EdgeInsets.only(left: 2),
//             child: Text(
//               title,
//               style: TextStyle(color: ColorPlate.yellow),
//             ),
//           )
//         ],
//       ),
//     );
//   }
// }

class TextGroup extends StatelessWidget {
  final String title, tag;
  final Color color;

  const TextGroup(
    this.title,
    this.tag, {
    Key key,
    this.color,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      child: Container(
        padding: EdgeInsets.symmetric(vertical: 0, horizontal: 8),
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            Text(
              title,
              style: StandardTextStyle.big.apply(color: color),
            ),
            Container(width: 4),
            Text(
              tag,
              style: StandardTextStyle.smallWithOpacity.apply(
                color: color?.withOpacity(0.6),
              ),
            ),
          ],
        ),
      ),
      onTap: () {
        if (tag == '关注') {
          Navigator.of(context).push(
            MaterialPageRoute(
                fullscreenDialog: true,
                builder: (context) {
                  return Theme(
                      data: ThemeColor.themecolor,
                      child: Material(
                        child: FollowPage(),
                      ));
                }),
          );
        }
      },
    );
  }
}

void httpgettoken() async {

  var url = Uri.parse("https://api.weixin.qq.com/sns/oauth2/access_token");
  var result = await http.post(
    url,
    body: {
      'appid': "wxf0495916cf6b6817",
      'secret': "0b537a7e8c74cefa63dc6935bd101187",
      'code': "063cND0w3cs6MW209B1w3oHpW02cND0s",
      "grant_type": "authorization_code" //固定字段
    },
      // encoding: Utf8Codec(),
  ).then((http.Response response) {
    if (response.statusCode == 200) {
      print(response.body);
    } else {
      print('error');
    }
  });
}


void httpgetWeChatMsg() async {
  var url = Uri.parse("https://api.weixin.qq.com/sns/userinfo");
  var result = await http.post(
    url,
    body: {
      'access_token': "47_V03Dp4-t6TkhLIb21fH6AIbYFy_0nYGLOHkZYhlkifslDNmFl_VuUWdb5MXNNA9LkqM6nCbKc-eRqDQ5LyvSPA1CznI-6RQYWvTshu0-6JK8_tr_r_O8Cih33QcV6HLcMA1zfEouW9AOg1QXHWQeAHAVKE",
      'openid': "oxMG55TZ2rOJs9SHr_oSHDlPonwI",
    },
    // encoding: Utf8Codec(),
  ).then((http.Response response) {
    if (response.statusCode == 200) {
      print(response.body);
    } else {
      print('error');
    }

  });

}
